'use strict';

var ctrl = module.exports = {};
var debug = require('debug'),
  log = debug('yozh:mo:formtoken:log'),
  error = debug('yozh:mo:formtoken:error'),
  verbose = debug('yozh:mo:formtoken:verbose'),
  uuid = require('uuid'),
  service = require('./user.service'),
  roleService = require('../role/role.service'),
  koajwt = require('koa-jwt'),
  tools = require('../../lib/tools'),
  config = require('../../config/config'),
  tokenCache = require('../../lib/cache')(config.tokenCache),
  errorsCache = require('../../lib/cache')(config.errorsCache),
  respData = require('../../config/json_resp_data');

var apiVersion = 'v1/',
  moduleName = 'formtoken',
  tokenType = 'formToken',
  liveTime = 3600;

/**
 * create a form token cache with ip, timestamp, livetime
 * @param {Function} next          [description]
 * @yield {[type]}   [description]
 */
ctrl.create = function *(next) {
  this.state.skipChectToken = true;
  var ip = tools.getClientIp(this.request);
  var date = Date();
  log('client ip: ', ip, 'create time: ', date);
  var token = koajwt.sign({
    createTime: date,
    type: tokenType
  }, config.secret);

  var links = respData.createLinks(apiVersion, moduleName, '');

  if (token) {
    yield tokenCache.set(token, JSON.stringify({clientIp: ip}));
    yield tokenCache.expire(token, liveTime);

    var data = respData.createData(moduleName, token);
    var datas = [];
    if (data) {
      datas.push(data);
    }

    this.status = 201;
    this.body = JSON.stringify({links: links, data: datas});
  } else {
    var errorId = uuid.v4();
    var errors = respData.createErrors(
      errorId,
      500,
      '01009',
      '生成表单token失败',
      tokenType,
      {
        cliebtIp: ip,
        createTime: date,
        type: tokenType,
        method: this.request.method,
        path: this.path
      }
    );
    yield errorsCache.set(errorId, JSON.stringify(errors));
    yield errorsCache.expire(errorId, 600);

    this.status = 500;
    this.body = JSON.stringify({links: links, errors: errors});
  }

  yield next;
};
